package cn.chiship.framework.upms.biz.base.service.impl;

import cn.chiship.framework.common.constants.SystemConfigConstants;
import cn.chiship.framework.common.pojo.vo.ConfigJson;
import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsNoticeSystemDto;
import cn.chiship.framework.upms.biz.system.service.UpmsNoticeService;
import cn.chiship.framework.upms.core.enums.NoticePriorityEnums;
import cn.chiship.framework.upms.core.enums.NoticeScopeEnums;
import cn.chiship.sdk.core.enums.UserTypeEnum;
import cn.chiship.sdk.core.util.PrintUtil;
import cn.chiship.sdk.third.ali.AliDySmsUtil;
import cn.chiship.sdk.third.core.model.BaseConfigModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;

/**
 * 异步消息通知发送
 */
@Component
public class AsyncMessageNotificationService {

	private static final Logger LOGGER = LoggerFactory.getLogger(AsyncMessageNotificationService.class);

	@Resource
	UpmsNoticeService upmsNoticeService;

	@Resource
	GlobalCacheService globalCacheService;

	/**
	 * 发送短信
	 * @param mobile
	 * @param template
	 * @param paramsMap
	 */
	@Async("asyncServiceExecutor")
	public void sendSms(String mobile, String template, Map<String, String> paramsMap) {
		PrintUtil.console("发布短信通知");
		try {
			ConfigJson configJson = globalCacheService
					.getSystemConfigJson(Arrays.asList(template, SystemConfigConstants.SIGN_CONTENT,
							SystemConfigConstants.SMS_ACCESS_KEY, SystemConfigConstants.SMS_SECRET_KEY));
			BaseConfigModel baseConfigModel = new BaseConfigModel(
					configJson.getString(SystemConfigConstants.SMS_ACCESS_KEY),
					configJson.getString(SystemConfigConstants.SMS_SECRET_KEY));
			AliDySmsUtil aliDySmsUtil = AliDySmsUtil.getInstance().config(baseConfigModel);
			aliDySmsUtil.load(configJson.getString(SystemConfigConstants.SIGN_CONTENT), configJson.getString(template));
			aliDySmsUtil.sendSms(mobile, paramsMap);
		}
		catch (Exception e) {
			LOGGER.error("短信发送失败！原因：{}", e.getLocalizedMessage());
		}
	}

	/**
	 * 发送站内信
	 * @param upmsNoticeSystemDto
	 */
	@Async("asyncServiceExecutor")
	public void sendSystemMsg(UpmsNoticeSystemDto upmsNoticeSystemDto) {
		try {
			PrintUtil.console("发布站内信");
			upmsNoticeService.sendSystemMsg(upmsNoticeSystemDto);
		}
		catch (Exception e) {
			LOGGER.error("站内信发送失败！原因如下", e);
		}
	}

}
